import React, { Suspense, useState, useEffect } from "react";
import {
  Route,
  Routes,
  useNavigate,
  useLocation,
  useParams,
  useSearchParams,
  Navigate,
} from "react-router-dom";
import routes from "./routes.js";
import { Mask, DotLoading, Toast } from "antd-mobile";
import store from "@/store";
import Api from "@/api";

const isLoading = (path) => {
  let {
      base: { info },
    } = store.getState(),
    checkList = ["/personal", "/store"];
  return !info && checkList.includes(path);
};
// 统一路由配置。不能把async家在这里，因为最终要返回一个 JSX 而不是 Promise
const Element = (props) => {
  let { component: Component, meta, path } = props;

  let isShow = !isLoading(path);
  let [_, setRandom] = useState(0);

  useEffect(() => {
    if (isShow) return;
    (async () => {
      // 先获取用户信息
      let res = await Api.userInfo();
      let info = res.data;
      if (!info) {
        // 还是没有信息，说明没登录，需要去重新登录
        Toast.show({
          icon: "fail",
          content: "请先登录",
        });
        return (
          <Navigate
            to={{
              pathname: "/login",
              search: `?to=${path}`,
            }}
          />
        );
      }
      // 如果获取到信息，说明已登录，派发任务信息存储到容器中
      store.dispatch(res);
      setRandom(+new Date());
    })();
  });

  // 修改页面的Title
  document.title = meta ? meta.title : "知乎日报-mobile";

  // 路由守卫设置

  // 获取路由信息，基于属性传递给组件
  const navigate = useNavigate(),
    location = useLocation(),
    params = useParams(),
    [usp] = useSearchParams();

  return !isShow ? (
    <Mask visible={true}>
      <DotLoading color="white" />
    </Mask>
  ) : (
    <Component
      navigate={navigate}
      location={location}
      params={params}
      usp={usp}
    />
  );
};

const RouterView = () => {
  return (
    <Suspense
      fallback={
        <Mask visible={true}>
          <DotLoading color="white" />
        </Mask>
      }
    >
      <Routes>
        {routes.map((route) => {
          let { name, path } = route;
          return (
            <Route key={name} path={path} element={<Element {...route} />} />
          );
        })}
      </Routes>
    </Suspense>
  );
};

export default RouterView;
